package org.winexpress

import grails.converters.deep.JSON
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;

class LoginController {

    def memberLogin = {
        def username = params['username']
        def password = params['password']
        
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/login/" + username + "/" + password).text

        JSONObject o  = new JSONObject(txt)
        
        if (o.has("404")) {
            if (o.get("404") == true) {
                flash.message = 'User not found.<br/><br/>'

                redirect(uri:"/memberLogin")
            }
        }
        else {
            if (password == o.password) {
                session.customerId = o.id
                session.customerUsername = o.username
                session.customerName = o.firstName

                println "Login Details: " + session.customerId + " " + session.customerName
            }
            else {
                flash.message = "Wrong credentials.<br/><br/>"
            }

            println "updateMemberLastLogin OK"

            redirect(uri:"/")
        }
    }
    
    def memberLogout = {
        session.customerId = null
        session.customerUsername = null
        session.customerName = null
        
        flash.message = "You have been logged out successfully. Thank you! Please come again!"
        
        redirect(uri:"/")
    }
}
